package com.vf.admin.fiwork.controller;

import com.alibaba.fastjson.JSONObject;
import com.vf.admin.client.common.ClientBaseController;
import com.vf.admin.client.common.ClientConstants;
import com.vf.admin.client.common.RedisKeys;
import com.vf.admin.client.service.AppRealNameService;
import com.vf.admin.client.service.AppSetupService;
import com.vf.admin.client.service.AppTaskRecordService;
import com.vf.admin.client.service.AppUserService;
import com.vf.admin.common.entity.Result;
import com.vf.admin.common.redis.RedisUtil;
import com.vf.admin.fiwork.util.SampleUtil;
import com.vf.admin.miaodong.entity.AppRealName;
import com.vf.admin.miaodong.entity.AppSetup;
import com.vf.admin.miaodong.entity.AppUser;
import com.vf.admin.utils.StringEx;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

import static com.vf.admin.utils.StringEx.isNull;

/**
 * 真人图片认证
 *
 * @author
 * @version 1.0.0
 * @ClassName AppRealNameController.java
 * @createTime 2021年07月21日 10:58:00
 */
@Controller
@RequestMapping("/app/ertification")
public class AppRealNameController extends ClientBaseController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    AppSetupService appSetupService;
    @Autowired
    AppUserService appUserService;
    @Autowired
    AppRealNameService appRealNameService;
    @Autowired
    AppTaskRecordService appTaskRecordService;
    @Autowired
    RedisUtil redisUtil;

    /**
     * 获取个人认证说明
     *
     * @Param: []
     * @return: com.vf.admin.common.entity.Result
     * @Author: zhouyunyi
     * @Date: 2021/10/21
     * @Time: 15:25
     */
    @RequestMapping("/getShiming")
    @ResponseBody
    public Result getShuoming() {
        try {
            Map<String, Object> map = new HashMap<>(16);
            AppSetup appSetup = appSetupService.get();
            map.put("shimingrenzheng", appSetup.getShimingrenzheng());
            return this.sucessJSON(map);
        } catch (Exception e) {
            logger.error("获取个人真人照片认证说明异常", e);
            return this.errorJSON("Error");
        }
    }

    /**
     * 获取关于我们协议
     *
     * @Param: []
     * @return: com.vf.admin.common.entity.Result
     * @Author: zhouyunyi
     * @Date: 2021/10/21
     * @Time: 15:27
     */
    @RequestMapping("/about")
    @ResponseBody
    public Result about() {
        try {
            Map<String, Object> map = new HashMap<>(16);
            AppSetup setup = appSetupService.get();
            map.put("shipinrenzheng", setup.getShipinrenzheng());
            return this.sucessJSON(map);
        } catch (Exception e) {
            logger.error("获取关于我们协议异常", e);
            return this.errorJSON("Error");
        }
    }

    /**
     * 验证用户上传的真人照片
     * @return
     */
    @RequestMapping("/uploadImage")
    @ResponseBody
    @Transactional
    public Result uploadImage(String image){
        Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
        if(userId==null) return errorJSON("Please login");
        AppRealName real = appRealNameService.getReal(userId);
        if(Objects.nonNull(real)) return errorJSON("Image authentication has been bound");
//        String image = "http://snoss.vigo-live.com/FhBFZa2TnnkCAfQTZD_gBe6puXmo";
//        String image = "http://snoss.vigo-live.com/FusSHFRTa3G8SxHyFZPi72Wx4n50";
        String info = SampleUtil.detect(image);
        JSONObject json = JSONObject.parseObject(info);
        if(json.getString("error_msg").equals("SUCCESS") && json.getInteger("error_code").equals(0)){
            AppRealName appRealName = new AppRealName();
            appRealName.setCreatetime(new Date());
            appRealName.setStatus(1);
            appRealName.setUserid(userId);
            appRealName.setIdnumjust(image);
            appRealNameService.save(appRealName);
        }else{
            return errorJSON("The picture does not meet the requirements, please re-upload");
        }
        return sucessJSON(info,"Success");
    }

    /**
     * 获取上传的个人照片
     * @return
     */
    @RequestMapping("/imageInfo")
    @ResponseBody
    public Result imageInfo(){
        Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
        if(userId==null) return errorJSON("Please login");
        AppRealName real = appRealNameService.getReal(userId);
        if(Objects.isNull(real)){
            return errorJSON("No photos uploaded");
        }else{
            return sucessJSON(real,"Success");
        }
    }


    /**
     * 2张真人照片比对
     * @return
     */
    @RequestMapping("/imageComparison")
    @ResponseBody
    public Result imageComparison(MultipartFile image) throws IOException {
        String imageOne = "http://snoss.vigo-live.com/FtzmagPapMQVbOqWwaQVa3blhyYd";
        String imageTwo = Base64.getEncoder().encodeToString(image.getBytes());
        if(SampleUtil.pk(imageOne, imageTwo)){
            return sucessJSON("YES");
        }
        return sucessJSON("NO");
    }


    /**
     * 上传视频认证
     *
     * @Param: [image 视频流]
     * @return: com.vf.admin.common.entity.Result
     * @Author: zhouyunyi
     * @Date: 2021/10/22
     * @Time: 10:48
     */
    @RequestMapping("/saveshipin")
    @ResponseBody
    public Result saveShipin(MultipartFile[] image) {
        try {
            //获取最新数据
            Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
            AppUser user = appUserService.get(userId);

            AppRealName appRealName = appRealNameService.getReal(user.getId());
            if(!StringUtils.isEmpty(appRealName)){
                if (!isNull(appRealName.getShipinstate())) {
                    //审核中，审核通过都不能再上传
                    if (appRealName.getShipinstate() == 1 || appRealName.getShipinstate() == 3) {
                        return this.sucessJSON("您已上传认证中，不可重复上传");
                    }
                }
            }
            String video = "";
            //上传：循环获取file数组中得文件
            StringBuffer stringBuffer = new StringBuffer();
            if (image != null && image.length > 0) {
                MultipartFile files = image[0];
                if (!files.isEmpty()) {
                    //判断视频大小
                    if (files.getSize() > 104857600) {
                        return this.errorJSON("视频大小超过限制");
                    }
                    //上传阿里云oss
                    Result results = appUserService.aliyunOssShipingUp(files);
                    if (results.getCode() != 0) {
                        return results;
                    }
                    //获取路径
                    String url = (String) results.getData();
                    //拼接
                    stringBuffer.append(url);
                }
            } else {
                return this.errorJSON("视频不能为空");
            }
            video = stringBuffer.toString();

            if (StringUtils.isEmpty(appRealName)) {
                //新增视频认证
                AppRealName realName = new AppRealName();
                realName.setShipinstate(3);//正在审核
                realName.setShipin(video);
                if (StringEx.isNull(user.getNick())) {
                    realName.setNick(user.getLoginname());
                } else {
                    realName.setNick(user.getNick());
                }
                realName.setPhone(user.getLoginname());
                realName.setPic(user.getPic());
                realName.setCreatetime(new Date());
                realName.setUserid(user.getId());
                appRealNameService.save(realName);

            } else {

                //修改视频认证信息
                appRealName.setPic(user.getPic());
                if (StringEx.isNull(user.getNick())) {
                    appRealName.setNick(user.getLoginname());
                } else {
                    appRealName.setNick(user.getNick());
                }
                appRealName.setPhone(user.getLoginname());
                appRealName.setShipin(video);
                appRealName.setShipinstate(3);//正在审核
                appRealNameService.save(appRealName);

            }
            return this.sucessJSON("保存成功");
        } catch (Exception e) {
            logger.error("上传视频认证异常", e);
            return this.errorJSON("视频上传认证异常");
        }
    }



}
